from config import config_map
from flask import Flask
from flask_restful import Api, Resource
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from flask_session import Session
from app.utils.commons import ReConverter
import logging
import redis

db = SQLAlchemy()
redis_store = None


def create_app(config_name):
    '''
    :param config_name: 创建app的类型
    :return: 返回一个配置好的flask app
    '''
    logging.basicConfig(level=logging.DEBUG,  # 控制台打印的日志级别
                        filename='logs/shop_log.txt',  # 将日志写入log_new.log文件中
                        filemode='a',  ##模式，有w和a，w就是写模式，每次都会重新写日志，覆盖之前的日志
                        # a是追加模式，默认如果不写的话，就是追加模式
                        format=
                        '%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'
                        # 日志格式
                        )
    config_class = config_map.get(config_name)
    app_v1 = Flask(__name__, instance_relative_config=True)
    # 通过类方式加载app的配置
    app_v1.config.from_object(config_class)
    CORS(app_v1, supports_credentials=True)
    # 初始化数据库对象
    db.init_app(app_v1)
    # 初始化redis链接对象
    global redis_store
    redis_store = redis.StrictRedis(host=config_class.REDIS_HOST, port=config_class.REDIS_PORT, db=2)
    # 为flask应用设置session
    Session(app_v1)
    # 为flask填充csrf防护
    # CSRFProtect(app)
    # 注册转换器
    app_v1.url_map.converters["re"] = ReConverter
    # 注册蓝图
    from app import api_v1
    app_v1.register_blueprint(api_v1.api, url_prefix='/api/v1.0')
    from app import web_html
    app_v1.register_blueprint(web_html.html)
    return app_v1
